<?php
/**
 * Displays pages for static content
 *
 * ACCESS: PUBLIC
 *
 * @author Chris Lunsford
 * @version 1.0
 */
class Xa extends Controller {
	
	/**
	 * Class constructor
	 */
	function __construct() {
		parent::__construct();
		
		$this->badger->checkRemember();
	}
	
	/******************** URL Functions ********************/
	
	function index() {
		$data = $this->_buildContent();
		$data['pagetype'] = 'nobg';
		$this->load->model('BlogModel');
		$this->load->model('ContentModel');
		$this->load->model('CalendarModel');
		$data['posts'] = $this->BlogModel->getPosts('public','published',4);
		$events = $this->CalendarModel->homepage(4);
		$data['info_seven'] = $this->ContentModel->getContent('info_707')->value;
		$data['info_cafe'] = $this->ContentModel->getContent('info_cafe')->value;
		if($events->num_rows()>0){
			foreach ($events->result() as $row){
				$sTime = strtotime($row->start);
				$eTime = strtotime($row->end);
				$startMonth = date("F",$sTime);
				$endMonth = date("F",$eTime);
				$startDay = date("j",$sTime);
				$endDay = date("j",$eTime);
				$sYear = date("Y",$sTime);
				$eYear = date("Y",$eTime);
				if(($startMonth==$endMonth) && ($sYear==$eYear)){
					$row->day = $startMonth;
					if($startDay==$endDay){
						$row->day .= " $startDay, $sYear";
					}
					else{
						$row->day .= " $startDay-$endDay, $sYear";
					}
				}
				else{
					if($sYear==$eYear){
						$row->day .= "$startMonth $startDay - $endMonth $endDay, $sYear";
					}
					else{
						$row->day .= "$startMonth $startDay, $sYear - $endMonth $endDay, $eYear";
					}
				}
			}
		}
		$data['events'] = $events;
		$data['extraJS'] = array('http://www.google.com/jsapi');											
		$this->load->view('xa/home', $data);
	}

	/**
	 * Displays about pages: "who we are" "what we're doing" "what we believe"
	 */
	function about() {
		$data = $this->_buildContent();
		if ($this->uri->segment(3) == "beliefs") {
			if($this->uri->segment(4) == "summary") {
				$data['pagetype'] = 'nobg';
				$this->load->view('xa/beliefs_summary', $data);
			}
			else
				$this->load->view('xa/beliefs', $data);
		} elseif ($this->uri->segment(3) == "what") {
			$this->load->view('xa/what', $data);
		} else {
			$this->load->view('xa/about', $data);
		}
	}
	
	/**
	 * Displays a page that gives contact info for rides to church
	 */
	function churchRide() {
		$data = $this->_buildContent();
		
		$this->load->view('xa/churchRide', $data);
	}

    /**
     * Shows the info & registration page for the Fall 2009 Halo tournament
     */
	function halo_tourney() {
		$data = $this->_buildContent();
		$this->load->view('xa/halo_tourney', $data);
	}

	function makeover() {
		$data = $this->_buildContent();
		$this->load->view('xa/makeover',$data);
	}

    /**
     * Shows info for Gary Habernas, related to his 2010 appearance at NCSU
     */
	function habermas() {
		$data = $this->_buildContent();
		$this->load->view('xa/habermas', $data);
	}
	
	function springretreat() {
		$data = $this->_buildContent();
		$this->load->view('xa/springretreat', $data);
	}
	
	
	/**
	 * Displays resource pages: "links" "books" "podcasts" and "international student resources"
	 */
	function resources() {
		$data = $this->_buildContent();
		if ($this->uri->segment(3) == "podcasts") {
			$this->load->view('xa/resources_podcasts', $data);
		} elseif ($this->uri->segment(3) == "videos") {
			$this->load->view('xa/resources_video',$data);
		} elseif ($this->uri->segment(3) == "books") {
			$this->load->view('xa/resources_books', $data);
		} elseif ($this->uri->segment(3) == "international") {
			$this->load->library('validation');
			$this->load->view('xa/resources_international', $data);
		} else {
			$this->load->view('xa/resources_links', $data);
		}
	}
	
	/**
	 * Displays contact submission form and contact email addresses
	 */
	function contact() {
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['email'] = "trim|required|valid_email";
		$rules['message'] = "trim|required";
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'Name';
		$fields['email']	= 'Email Address';
		$fields['message'] = 'Message';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$this->load->view('xa/contact',$data);
		} else {
			$this->session->set_flashdata('msg_info', 'Thanks for contacting us.  We\'ll get in touch with you soon.');
					
			$name = $this->input->post('name',TRUE);
			$email = $this->input->post('email',TRUE);
			$message = $this->input->post('message',TRUE);
				
			//send Brian an email
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to('brianmindyxa@gmail.com');
			$this->email->subject('New Contact Form Submission');
			$this->email->message('Name: ' . $name .'. Email: ' . $email .' Message: '. $message);
			
			$this->email->send();
			$this->email->set_newline("\r\n");	
			$this->email->clear();
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to($email);
			$this->email->subject('Thanks for contacting us - Chi Alpha at NCSU & Meredith');
			$this->email->message('Your message has been forward to one of our staff members.  We\'ll get in touch with you soon. Thanks, Chi Alpha Christian Fellowship \n Your message:'. $message);
			
			$this->email->send();
			redirect('xa/contact');
		}
	}
	
	function _getDateString($day, $hour) {
		$str = "2010-";
		if(strpos($day, "Nov.") !== false) {
			$str = $str . "11-";
		} else  if(strpos($day,"Dec.") !== false) {
			$str = $str . "12-";
		} else {
			$str = $str . "12-";
		}
		
		//grab the date
		$arr = split(" ", $day);
		$str .= $arr[1] . " ";
		
		//get the hour
		$arr = split("-", $hour);
		$h = "";
		$i = (int)$arr[0];
		
		if(strpos($hour, "pm") !== false || strpos($hour, "11-12am") !== false) {
			if($i  < 11 || strpos($hour,"11-12am")!==false) {
				$i += 12;
			}
		}
		
		$str .= $i . ":00:00";
		
		return $str;
	}
	
	/**
	 * Displays submission form for live week
	 */
	 
	 
	function liveweek() {
					
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['email'] = "trim|required|valid_email";
		//$rules['message'] = "trim|required";
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'Name';
		$fields['email']	= 'Email Address';
		$fields['day'] = 'Day';
		$fields['hour'] = 'Hour';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
						log_message('debug', "Hello!!!!!!");
			$data = $this->_buildContent();
			$this->load->view('xa/live_week',$data);
		} else {

			$this->session->set_flashdata('msg_info', 'Thanks for signing up for live week!  You should receive a confirmation e-mail soon. (Check your spam folder if you can\'t find it');
					
			$name = $this->input->post('name',TRUE);
			$email = $this->input->post('email',TRUE);
			$day = $this->input->post('day',TRUE);
			$hour = $this->input->post('hour',TRUE);
			//$this->session->set_flashdata('msg_info', 'day:\t' . $this->_getDateString($day,$hour) . "  hour:\t" . $day);
			//send liveweek an email
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to('liveweekprayer@gmail.com');
			$this->email->subject('New Submission: Untitled Form 11');
			//$this->email->set_newline("\r\n");
			$this->email->message('Student name: '  . $name  . "\nEmail: " . $email . " \nDay: ". $day . " \nHour: ". $hour);
			
			//insert into database
			//convert day/hour into date time str
			$dateStr = $this->_getDateString($day, $hour);
			$toInsert = array('name' => $name, 
				'email' => $email,
				'date' => $dateStr);
			
			$this->db->insert('liveweek', $toInsert);
			log_message('debug', "after insert");
			log_message('debug', implode(",", $toInsert));

			//echo($toInsert);
			
			$this->email->send();
			$this->email->set_newline("\r\n");	
			$this->email->clear();
			$this->email->from('donotreply@xa-ncsu.com','Live Week - Fall, 2009');
			$this->email->to($email);
			$this->email->subject('Live Week - Fall, 2010');
			$this->email->message('Thanks for signing up for Live Week!  Your timeslot is: '. $day . ' from ' . $hour);
			
			$this->email->send();
			redirect('xa/liveweek');
		}
	}
	/*
		 function reminders() {
                $data = $this->_buildContent();
                $config = Array(
                    'protocol' => 'smtp',
                    'smtp_host' => 'ssl://smtp.googlemail.com',
                    'smtp_port' => 465,
                    'smtp_user' => 'liveweekprayer@googlemail.com',
                        'smtp_pass' => 'ncsuprayer',
                        'newline' => "\r\n"
                );
                $this->load->library('email', $config);

                $result = $this->db->query("SELECT * FROM liveweek_timeslots WHERE date >= '2010-04-28 07:00:00' and date <= '2010-04-29 20:00:00'");
                $count = 0;
                        
                foreach($result->result_array() as $row) {
                        $count++;
                        
                        $email = $row['email'];
                        $day = strtotime($row['date']);
                        $hour = $day;
                        
                        $this->email->from('liveweekprayer@gmail.com','Live Week Prayer - Spring, 2010');
                        $this->email->to($email);
                        $this->email->subject('Live Week Prayer Reminder');
                        $message = "Thanks for signing up for Live Week!  This is a reminder e-mail for your timeslot. (Which may be late for some folks).  You're signed up at the following time:\n";
                        $message .= "\nDay:\t" .  date("l, F j", $day) . "\n";
                        $message .= "Time:\t" . date("g:ia", $hour) . "\n";
                        $message .= "\nA request:  If you're praying at 8am, please show up early if possible to help set up.  ";
                        $message .= "If you're praying at 7pm, please hang around a little bit afterwards to help clean up.  ";
                        $message .= "For everyone else, please show up a few minutes early, and wait until someone shows up for the next slot after your slot is up.  Thanks again!\n\n";
                        $message .= "In Christ,\nThe Live Week team";
                        $this->email->message($message);
                        //$this->email->send();
                        log_message('debug', $this->email->print_debugger());
                        //log_message('debug', $email . "-\n". $message);
                        
                }

                
        } */

	
	
	
	function live_week_schedule() {
		$data = $this->_buildContent();
		$this->load->view('xa/live_week_schedule');
	}
	
	/**
	 * Displays map and directions to the XA House
	 */
	function house() {
		$data = $this->_buildContent();
		$data['extraBody'] = 'onload="load()" onunload="GUnload()"';
		$this->load->view('xa/house', $data);
	}
	
	/**
	 * Displays a google calendar -> will be replaced with our own calendar function
	 * 
	 * Google Calendar depreciated. This is now used to  to display information on 707 and cafe
	 */
	function events() {
		$data = $this->_buildContent();
		if ($this->uri->segment(3) == "largegroup") {
			$this->load->view('xa/events_largegroup', $data);
		} elseif ($this->uri->segment(3) == "cafe") {
			$this->load->view('xa/events_cafe', $data);
		} else {
			redirect('xa');
		}
	}
	/*
	function reminders() {
		$data = $this->_buildContent();
		$config = Array(
		    'protocol' => 'smtp',
		    'smtp_host' => 'ssl://smtp.googlemail.com',
		    'smtp_port' => 465,
		    'smtp_user' => 'liveweekprayer@googlemail.com',
			'smtp_pass' => 'ncsuprayer',
			'newline' => "\r\n"
		);
		$this->load->library('email', $config);

		$result = $this->db->query("SELECT * FROM liveweek");
		$count = 0;
			
		foreach($result->result_array() as $row) {
			$count++;
			
			$email = $row['email'];
			$day = strtotime($row['date']);
			$hour = $day;
			
			$this->email->from('liveweekprayer@gmail.com','Live Week Prayer - Fall, 2009');
			$this->email->to($email);
			$this->email->subject('Live Week - Success!');
			$message = "To everyone who joined us in the prayer tent this week, thanks! It was an amazing week that we couldn't have asked more of.  We ended up having about 140 people from 10 different campus ministries join us in blessing N.C. State for 45 hours in the middle of campus!";
			$message .= "\n\n As we pray over this event and look to set it in motion for next semester, we would love to hear any encouraging stories of how God used Live Week for his glory. Please feel free to send them to me or email them to liveweekprayer@gmail.com. Along with that, if you have any suggestions or comments, send those along too.";
			$message .= "\n\n That said, thank you all for faithfully stepping out to to glorify the Lord this week through your prayers. We fully believe that our prayers were heard and will be answered, and as they are, the Kingdom of God will continue to advance on our campus, more than ever before!";
			$message .= "\n\n So God bless you and pray on!\n\n Sean \n\n P.S. We found a blue blanket at the tent today. Let me know if it's yours.";
			$this->email->message($message);
					$this->email->send();
			log_message('debug', $this->email->print_debugger());
			//log_message('debug', $email . "-\n". $message);
			
		}

		
	}*/
	
	function lifegroups() {
		$data = $this->_buildContent();
        $grp = $this->uri->segment(3);

/**        if ($grp == "pop") {
            $this->load->view("xa/lifegroups/pop");
        } elseif($grp == "minorprophets") {
            $this->load->view("xa/lifegroups/minorprophets");
        } elseif($grp == "guysgroup") {
            $this->load->view("xa/lifegroups/guysgroup");
        } elseif($grp == "
        **/

        if($grp == "") {
            $this->load->view("xa/lifegroups");
        } else {
            $this->load->view("xa/lifegroups/" . $grp);
        }
			
	}
	
	/******************* Task Functions *******************/

	/**
	 * Displays and processes form for requesting a bible in your language
	 * Found on international resources page.
	 */
	function biyl() {
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['language'] = "trim|required";
		$rules['email'] = "trim|required|valid_email";
		$rules['phone'] = "trim";
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'Name';
		$fields['language']	= 'language';
		$fields['email']	= 'Email Address';
		$fields['phone'] = 'Phone number';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$this->load->view('xa/resources_international',$data);
		} else {
			$this->session->set_flashdata('msg_info', "We\'ve received your submission.  We\'ll be in touch."); 
			$post['name'] = $this->input->post('name',TRUE);
			$post['language'] = $this->input->post('language',TRUE);
			$post['email'] = $this->input->post('email',TRUE);
			$post['phone'] = $this->input->post('phone',TRUE);
			$this->load->model('ContentModel');
			$this->ContentModel->createBIYL($post);
				
			//send Brian an email
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to('brianmindyxa@gmail.com');
			$this->email->subject('New Bible in Your Language Submission');
			$this->email->message('Name: ' . $post['name'] .'. Language: ' . $post['language'] .'. Email: ' . $post['email'] .'. Phone: ' . $post['phone'] .'.');
			
			$this->email->send();

			redirect('xa/resources/international');
		}

	}
	
	/**
	 * Displays and processes form for sending in a prayer request
	 * Found on international resources page.
	 */
	function prayer() {
		$this->load->helper(array('form', 'url'));

		$this->load->library('form_validation');
		
		$config = array(
		               array(
							'field'	   => 'email',
							'label'    => 'Email',
							'rules'    => 'trim|required|xss_clean'
							),
						array(
			                     'field'   => 'prayer', 
			                     'label'   => 'Prayer Request', 
			                     'rules'   => 'trim|required|xss_clean'
								),
						array(
								 'field'   => 'anonymous',
								 'label'   => 'anonymous',
								 'rules'   => '')
						);
		
		$this->form_validation->set_rules($config);
		
	
		$this->form_validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->form_validation->run() == FALSE) {
			$data = $this->_buildContent();
			$data['pagetype'] = 'nobg';
			$this->load->view('xa/prayer',$data);
		} else {
			$this->session->set_flashdata('msg_info', "We've received your submission.  You'll be in our prayers."); 
			$post['email'] = $this->input->post('email',TRUE);
			$post['prayer'] = $this->input->post('prayer',TRUE);
			if($this->input->post('anonymous')=='anonymous') $post['anonymous'] = 'yes';
			else $post['anonymous'] = 'no';
			$this->load->model('ContentModel');
			$this->ContentModel->createPrayer($post);
				
			redirect('xa');
		}

	}

	/**
	 * Sends an email to admin from contact form submission
	 */
	function contactEmail() {
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['email'] = "trim|required|valid_email";
		$rules['message'] = "trim|required";
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'Name';
		$fields['email']	= 'Email Address';
		$fields['message'] = 'Message';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$this->load->view('xa/contact',$data);
		} else {
			$this->session->set_flashdata('msg_info', 'Thanks for contacting us.  We\'ll get in touch with you soon.');
					
			$name = $this->input->post('name',TRUE);
			$email = $this->input->post('email',TRUE);
			$message = $this->input->post('message',TRUE);
				
			//send Brian an email
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to('brianmindyxa@gmail.com');
			$this->email->subject('New Contact Form Submission');
			$this->email->message('Name: ' . $name .'. Email: ' . $email .' Message: '. $message);
			
			$this->email->send();
			redirect('xa/contact');
		}
	}
	
	/**
	 * Sends an email to admin from contact form submission
	 */
	function contactLifegroup() {
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['email'] = "trim|required|valid_email";
		$rules['message'] = "trim|required";
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'Name';
		$fields['email']	= 'Email Address';
		$fields['message'] = 'Message';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$data['pagetype'] = 'nobg';
			$this->load->view('xa/lifegroups', $data);
		} else {
			$this->session->set_flashdata('msg_info', 'Thanks for contacting us.  We\'ll get in touch with you soon.');
					
			$name = $this->input->post('name',TRUE);
			$email = $this->input->post('email',TRUE);
			$message = $this->input->post('message',TRUE);
				
			//send Brian an email
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to('brianmindyxa@gmail.com');
			$this->email->subject('New Contact Form Submission');
			$this->email->message('Name: ' . $name .'. Email: ' . $email .' Message: '. $message);
			
			$this->email->send();
			redirect('xa/contact');
		}
	}
	
	/*
	 * Supplies user-specific information to the interface for customization
	 * REQUIRED DATA ARRAY PARAMS:
	 * pagetype = page, page-admin, nobg
	 * loggedin = isset
	 */
	function _buildContent() {
		$data = array();
		if ($this->session->flashdata('msg_info')) $data['msg_info'] = $this->session->flashdata('msg_info');
		if ($this->session->flashdata('msg_error'))	$data['msg_error'] = $this->session->flashdata('msg_error');
		
		if ($this->session->userdata('loggedin')) {
			$this->load->model('UserModel');
			$user = $this->UserModel->getUserByName($this->session->userdata('username'));
			
			$data['con_user'] = $user;
			$data['loggedin'] = TRUE;
			
			//is admin?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('admin'))) {
				$data['admin_tab'] = TRUE;
			}
			
			//is prayer team?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('lg_pop'))) {
				$data['prayer_tab'] = TRUE;
			}
		}
		
		return $data;
	}
    function photos() {
    $data = array();
        $this->load->view('xa/photos',$data);
    }
    function uploadPhotos() {
    $data = array();
        $this->load->view('xa/uploadPhotos',$data);
    }
}
?>
